<template>
  <div>
    <el-dialog
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      :title="title"
      :visible.sync="accrssoryVisible"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <p slot="title">{{ title }}</p>
      <div class="material-search-container">
        <el-row>
          <el-col :span="24">
            <div class="chioseFileDiv">
              <span style="margin-left: 35px">上传附件</span>
              <span style="margin-left: 5px; font-size: 1px; color: blue"
                >每个文件上传不能超过10兆</span
              >
              <div style="float: right; margin-right: 45px">
                <el-button
                  slot="trigger"
                  v-loading="uploadLoad"
                  size="small"
                  icon="el-icon-paperclip"
                  type="primary"
                  @click="choiseFile()"
                  >点击上传</el-button
                >
              </div>
              <el-upload
                ref="upload"
                class="base-upload"
                name="FilePath"
                :multiple="true"
                action
                :headers="headers"
                :show-file-list="false"
                :show-upload-list="false"
                :accept="accept"
                :before-upload="beforeUpload"
                :on-change="upload"
                :auto-upload="false"
                :file-list="fileList"
              ></el-upload>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div>
              <el-table
                ref="table"
                :data="tableData"
                style="width: 100%"
                height="300px"
              >
                <el-table-column
                  prop="originalFileName"
                  label="文件名称"
                ></el-table-column>
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column label="操作" width="140">
                  <template slot-scope="{ row }">
                    <div class="base-table-operation">
                      <el-link type="primary" @click="downLoadUnit(row)"
                        >下载</el-link
                      >&nbsp;&nbsp;&nbsp;&nbsp;
                      <el-link type="primary" @click="selectUnit(row)"
                        >查看</el-link
                      >&nbsp;&nbsp;&nbsp;&nbsp;
                      <el-link type="danger" @click="deleteUnit(row)"
                        >删除</el-link
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <BasePagination
                :total="pagination.total"
                :page-index="pagination.pageIndex"
                :page-size="pagination.pageSize"
                @sizeChange="sizeChange"
                @changePage="currentChange"
              />
            </div>
          </el-col>
        </el-row>
        <BasePreviewFile
          v-if="previewFileShow"
          :preview-file-show.sync="previewFileShow"
          :preview-file="filepreview"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "../../../utils/auth";
// import PreviewFileDialog from "./PreviewFileDialog.vue";
import {
  getList,
  create,
  DeleteByEntrustOrderId,
} from "../../../api/EntrustManage/EntrustFile";
import { DownloadEntrustFile } from "../../../api/EntrustManage/EntrustFile";
import { formdataify } from "../../../utils/index";
import { GetStaticFileInfo } from "@/api/Base";

export default {
  name: "AccessoryDialog",
  components: {
    // PreviewFileDialog,
  },
  props: {
    accrssoryVisible: {
      type: Boolean,
      default: false,
    },
    entrustOrderId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploadLoad: false,
      title: "委托单附件",
      headers: { Authorization: getToken() },
      accept: ".pdf,.doc,.xls,.docx,.xlsx,.png,.jpg",
      // 表格数据
      tableData: [],
      // 文件集合
      fileList: [],
      // 上传文件类型
      businessType: "30",
      fileSize: 11200,
      fileCount: 0,
      previewFileShow: false,
      filepreview: {
        fileName: "",
        url: "",
        storageFileName: "",
      },
      filterForm: {
        foreignKeyId: this.entrustOrderId,
      },
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  watch: {},
  created() {
    this.getEntrustFileList();
  },
  methods: {
    // 切换页码
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getEntrustFileList();
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
      this.getEntrustFileList();
    },
    // 查询附件
    getEntrustFileList() {
      getList({ ...this.pagination, ...this.filterForm }).then((res) => {
        this.tableData = res.data.dataList ? res.data.dataList : [];
        this.pagination.total = res.data.total;
      });
    },

    // 删除
    deleteUnit(row) {
      var idList = [];
      idList.push(row.id);
      this.deleteEntrustFile(idList);
    },
    // 删除
    deleteEntrustFile(data) {
      var idList = data;
      DeleteByEntrustOrderId({ id: idList }).then((res) => {
        this.getEntrustFileList();
      });
    },
    // 查看
    selectUnit(row) {
      // 这里确定数据源
      this.filepreview.fileName = row.originalFileName; // 文件名称（包括后缀名）storageFileName
      this.filepreview.storageFileName = row.storageFileName;
      var houzui = this.filepreview.storageFileName.split(".")[1];
      // var houzuiArray = ["xlsx", "xls", "jpg", "png", "pdf","docx"];
      var houzuiArray = ["pdf", "docx", "doc"];
      if (houzuiArray.indexOf(houzui) === -1) {
        this.$message.warning("文件预览只支持Word,PDF");
        return;
      }
      this.filepreview.url = row.filePath;
      this.previewFileShow = true;
    },
    // 通过文件下载url拿到对应的blob对象
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    // 下载文件js模拟点击a标签进行下载
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },
    // 下载
    downLoadUnit(row) {
      DownloadEntrustFile({ id: row.id }).then((res) => {
        if (res.code === 200) {
          // var fileUrl = `${this.$baseProtocol}//${res.data.filePath}`;
          var fileUrl = `${res.data.filePath}`;
          GetStaticFileInfo(fileUrl, res.data.originalFileName)
          // this.getBlob(fileUrl).then((blob) => {
          //   this.saveAs(blob, res.data.originalFileName);
          // });
        } else {
          this.$message.error("未找到文件,请联系管理员");
        }
      });
    },
    // 关闭弹框
    handleClose() {
      // 清空已选择的文件
      this.$emit("update:accrssoryVisible", false);
    },
    // 上传文件
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 上传完成
    upload(file, fileList) {
      this.uploadLoad = true;
      this.fileCount = fileList.length;
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        var data = {
          foreignKeyId: this.entrustOrderId,
          storageFileName: res.data.newFileName,
          filePath: res.data.filePath,
          originalFileName: res.data.fileName,
        };
        create(data)
          .then((res) => {
            this.getEntrustFileList();
            this.uploadLoad = false;
          })
          .catch(() => {
            this.uploadLoad = false;
          });
      });
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      var testmsg = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(testmsg);
      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(`请选择${this.accept}格式`);
      }
      const checkSize = file.size / 1024 < this.fileSize;
      if (!checkSize) {
        this.uploadLoad = false;
        this.$message.error(`文件必须小于${this.fileSize}KB！`);
      }
      return checkFormat && checkSize;
    },
  },
};
</script>
<style lang="scss" scoped>
.chioseFileDiv {
  background-color: #f1f8ff;
  height: 45px;
  line-height: 45px;
}
</style>

